package com.cheer.ba.view.base;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.smileyloadingview.SmileyHeaderView;
import com.bigkoo.svprogresshud.SVProgressHUD;
import com.cheer.ba.R;
import com.cheer.ba.cache.preference.Session;
import com.cheer.ba.constant.IntentCode;
import com.cheer.ba.presenter.IPresenter;
import com.cheer.ba.service.NetBroadCastReciver;
import com.cheer.ba.utils.NetUtil;
import com.cheer.ba.view.activity.LoginAty;
import com.cheer.ba.view.dialog.DialogUtils;
import com.cheer.ba.widget.callback.I_SkipActivity;

import butterknife.ButterKnife;

/**
 * basefragment 的基类
 */
public abstract class BaseFrg extends Fragment implements IViewController, I_SkipActivity, NetBroadCastReciver.NetEvent {
    protected String TAG;
    protected IPresenter presenter;
    protected boolean isViewInited = false;
    private String name;

    public Activity frg;

    private boolean isAddIn = false;
    private Dialog dialog;

    private int netMobile;

    public static NetBroadCastReciver.NetEvent mNetEvent;

    public BaseFrg() {
        TAG = getClass().getSimpleName();
    }

    public String getName() {
        return name;
    }

    /**
     * 如果是添加进FrameLayout里的，设置此标记，以便控制Fragment生命周期
     *
     * @param addIn
     */
    public void setAddIn(boolean addIn) {
        isAddIn = addIn;
    }


    public void setName(String name) {
        this.name = name;
        TAG += ":" + name;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");
        this.frg = getActivity();
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d(TAG, "onCreateView");
        View view = loadView(inflater);
        if (view == null) {
            view = loadView(inflater, null);
        }
        ButterKnife.bind(this, view);
        initPresenter();
        if (presenter != null) {
            presenter.attachView(this);
        }
        mNetEvent = BaseFrg.this;
        inspectNet();
        initView();
        initData();
        isViewInited = true;
        return view;
    }

    /**
     * 初始化时判断有没有网络
     */
    public boolean inspectNet() {
        this.netMobile = NetUtil.getNetWorkState(frg);
        return isNetConnect(netMobile);
    }

    /**
     * 网络变化之后的类型
     */
    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect(netMobile);
    }

    /**
     * 判断有误网络
     *
     * @return true 有 ，false 没有
     */
    public boolean isNetConnect(int net) {
        if (net == 1) {
            return true;
        } else if (net == 0) {
            return true;
        } else if (net == -1) {
            return false;
        }
        return false;
    }

    @Override
    public void initPresenter() {
        Log.d(TAG, "initPresenter");
    }

    @Nullable
    @Override
    public View loadView(LayoutInflater inflater, View childView) {
        return null;
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "onStart");
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d(TAG, "onResume isAddIn:" + isAddIn);
        if (isAddIn) {
            if (isVisible()) {
                onVisible();
            }
        } else {
            if (getUserVisibleHint()) {
                onVisible();
            }
        }
    }

    @Override
    public void showLoading() {
        Activity activity = getActivity();
        if (activity != null
                && activity instanceof IViewController) {
            ((IViewController) activity).showLoading();
        }
    }

    @Override
    public void hideLoading() {
        Activity activity = getActivity();
        if (activity != null
                && activity instanceof IViewController) {
            ((IViewController) activity).showLoading();
        }
    }

    @Override
    public <T> void updateView(T t) {
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, boolean loadMore, String tag) {
    }

    @Override
    public <T> void updateViewWithTag(T t, String tag) {
    }

    @Override
    public <T> void updateViewWithLoadMore(T t, int flag, String str, boolean loadMore, boolean direction, int size) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string, boolean loadMore) {
    }

    @Override
    public void onLoadingStatus(IViewController mView, boolean isHandler, int loadingStatus, int flag, String string, boolean loadMore, boolean isDirection) {
    }

    @Override
    public void handlerByPage(int flag1, int flag2) {
    }

    @Override
    public void handlerByPage(int flag1, int flag2, String string) {
    }

    @Override
    public void handlerByPage(int flag1, int flag2, boolean loadMore) {
    }

    @Override
    public void handlerByPage(int flag1, int flag2, boolean loadMore, boolean direction) {
    }

    /**
     * 用户是否登录
     *
     * @param isShowDialog 是否显示弹出框 true 显示
     */
    public boolean isLogin(boolean isShowDialog) {
        if (Session.getUserIsLogin()) {
            return true;
        } else {
            if (isShowDialog) {
                showLoginDialog();
            } else {
                Intent login = new Intent(frg, LoginAty.class);
                startActivityForResult(login, IntentCode.Login.LOGIN_REQUEST_CODE);
            }
            return false;
        }
    }

    /**
     * 弹出登录提示框
     */
    public void showLoginDialog() {
        if (isDetached() || getActivity() == null) {
            return;
        }

        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
        View view = getActivity().getLayoutInflater().inflate(R.layout.login_remind, null, false);
        TextView mTvTitle = (TextView) view.findViewById(R.id.id_remind_login_txt);
        mTvTitle.setText(getString(R.string.login_remind));
        mTvTitle.setSingleLine(false);
        TextView mTxtCancel = (TextView) view.findViewById(R.id.id_login_cancel_txt);
        mTxtCancel.setText(getString(R.string.login_look_again));
        mTxtCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        TextView mTxtConfirm = (TextView) view.findViewById(R.id.id_login_confirm_txt);
        mTxtConfirm.setText(getString(R.string.login_with_space));
        mTxtConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent login = new Intent(frg, LoginAty.class);
                startActivityForResult(login, IntentCode.Login.LOGIN_REQUEST_CODE);
            }
        });
        dialog = DialogUtils.selfDialog(getActivity(), view, true);
        dialog.show();
    }

    @Override
    public boolean hasDataInPage() {
        return false;
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.d(TAG, "onPause");
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop");
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.d(TAG, "onDestroyView");
        isViewInited = false;
        if (presenter != null) {
            presenter.detachView();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy");
//        if (getActivity() != null) {
//            RefWatcher refWatcher = App.getRefWatcher(getActivity());
//            refWatcher.watch(this);
//        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        Log.d(TAG, "setUserVisibleHint:" + isVisibleToUser);
        if (isViewInited) {
            if (getUserVisibleHint()) {
                onVisible();
            } else {
                onInVisible();
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        Log.d(TAG, "onHiddenChanged:" + hidden);
        if (isViewInited) {
            if (!isHidden()) {
                onVisible();
            } else {
                onInVisible();
            }
        }
    }

    /**
     * Fragment可见时回掉
     */
    protected void onVisible() {
        Log.d(TAG, "onVisible");
    }

    /**
     * Fragment隐藏时回掉
     */
    protected void onInVisible() {
        Log.d(TAG, "onInVisible");
    }

    /**
     * 指定Activity跳转，不带参数
     *
     * @param claz 组件名
     */
    protected void jump(Class<? extends Activity> claz) {
        jump(claz, null);
    }

    /**
     * 指定Activity跳转，带参数
     *
     * @param claz 组件名
     * @param data 参数
     */
    protected void jump(Class<? extends Activity> claz, Bundle data) {
        Intent intent = new Intent(getContext(), claz);
        if (data != null) {
            intent.putExtras(data);
        }
        startActivity(intent);
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Class<?> cls) {
        showActivity(aty, cls);
        aty.finish();
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Intent it) {
        showActivity(aty, it);
        aty.finish();
    }

    /**
     * skip to @param(cls)，and call @param(aty's) finish() method
     */
    @Override
    public void skipActivity(Activity aty, Class<?> cls, Bundle extras) {
        showActivity(aty, cls, extras);
        aty.finish();
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Class<?> cls) {
        Intent intent = new Intent();
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Intent it) {
        aty.startActivity(it);
    }

    /**
     * show to @param(cls)，but can't finish activity
     */
    @Override
    public void showActivity(Activity aty, Class<?> cls, Bundle extras) {
        Intent intent = new Intent();
        intent.putExtras(extras);
        intent.setClass(aty, cls);
        aty.startActivity(intent);
    }

    /**
     * 弹出框消失
     */
    public void SVProgressHUDDismiss(Context context) {
        if (null == context) {
            return;
        }
        if (SVProgressHUD.isShowing(context)) {
            SVProgressHUD.dismiss(context);
        }
    }

    /**
     * 进入系统设置界面
     */
    protected void requestPermission(int requestCode) {
        // TODO Auto-generated method stub
        // 6.0以上系统才可以判断权限

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.BASE) {
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {// 运行系统在5.x环境使用
            // 进入设置系统应用权限界面
            Intent intent = new Intent(Settings.ACTION_SETTINGS);
            startActivity(intent);
            return;
        }
        return;
    }

    //设置上次刷新的时间
    //mRefresh.restoreLastRefreshTime(lastRefreshTime);
    //XRefreshView不仅支持手势下拉刷新，也支持按钮点击开始刷新，
    //mRefresh.startRefresh();

    /**
     * @param mRefresh       刷新控件
     * @param isUpRefresh    是否可以上拉刷新
     * @param isLoadMore     是否加载更多
     * @param isAutoRefresh  是否可以自动刷新
     * @param isAutoLoadMore 是否滑动到底部自动加载更多
     */
    public void setXRefreshView(XRefreshView mRefresh, boolean isUpRefresh, boolean isLoadMore, boolean isAutoRefresh, boolean isAutoLoadMore, View mHeadView, View mFootView) {
        // 设置是否可以上拉刷新
        mRefresh.setPullLoadEnable(isUpRefresh);
        //是否加载更多
        mRefresh.setPullLoadEnable(isLoadMore);
        //设置是否可以自动刷新
        mRefresh.setAutoRefresh(isAutoRefresh);
        //滑动到底部自动加载更多,目前只做了Abslistview和Recylerview的,true会自动加载更多.
        // false则相反。传入false的话，如果是listview，需要上拉才能加载更多，如果是Recylerview，则会需要点击才能加载更多。就像这样
        mRefresh.setAutoLoadMore(isAutoLoadMore);

        //如果需要在手指横向移动的时候，让XRefreshView不拦截事件
        mRefresh.setMoveForHorizontal(true);
        //设置当下拉刷新完成以后，headerview和footerview被固定的时间
        //注:考虑到ui效果，只有时间大于1s的时候，footerview被固定的效果才会生效
        mRefresh.setPinnedTime(1000);
        //刷新时，不让里面的列表上下滑动
        mRefresh.setPinnedContent(false);
        if (null != mHeadView) {
            mRefresh.setCustomHeaderView(mHeadView);
        }
        if (null != mFootView) {
            mRefresh.setCustomFooterView(mFootView);
        }
    }

    /**
     * 停止下拉刷新
     *
     * @param mRefresh
     * @param time
     */
    public void stopRefresh(final XRefreshView mRefresh, int time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.stopRefresh();
            }
        }, time);
    }

    /**
     * 停止加载更多
     *
     * @param mRefresh
     * @param time
     */
    public void stopLoadMore(final XRefreshView mRefresh, int time) {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mRefresh.stopLoadMore();
            }
        }, time);
    }
}
